package com.gitee.wsl.compose.ui.richtext.edit.model.paragraph.ext

import androidx.compose.ui.util.fastForEach
import androidx.compose.ui.util.fastForEachReversed
import com.gitee.wsl.compose.ui.richtext.edit.model.span.ext.trimEnd
import com.gitee.wsl.compose.ui.richtext.edit.model.span.ext.trimStart
import com.gitee.wsl.compose.ui.richtext.edit.model.paragraph.RichParagraph

/**
 * Trim the rich paragraph
 */
fun RichParagraph.trim() {
    val isEmpty = trimStart()
    if (!isEmpty)
        trimEnd()
}

/**
 * Trim the start of the rich paragraph
 *
 * @return True if the rich paragraph is empty after trimming, false otherwise
 */
fun RichParagraph.trimStart(): Boolean {
    children.fastForEach { richSpan ->
        val isEmpty = richSpan.trimStart()

        if (!isEmpty)
            return false
    }

    return true
}

/**
 * Trim the end of the rich paragraph
 *
 * @return True if the rich paragraph is empty after trimming, false otherwise
 */
fun RichParagraph.trimEnd(): Boolean {
    children.fastForEachReversed { richSpan ->
        val isEmpty = richSpan.trimEnd()

        if (!isEmpty)
            return false
    }

    return true
}